package com.hyzh.hj212.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.hyzh.hj212.dmo.AirEnvVO;
import com.hyzh.hj212.dmo.StatsDataVO;
import com.hyzh.hj212.dmo.entity.record.AirRecordEntity;
import com.hyzh.hj212.enterprise.CommandCodeEnum;
import com.hyzh.hj212.enterprise.FieldCodeEnum;
import com.hyzh.hj212.enterprise.TypeToCommandEnum;
import com.hyzh.hj212.repository.AirRecordRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;


/**
 * @author songkui
 * @since 2024/6/20 17:13
 */
@Service
@Slf4j
@AllArgsConstructor
public class LatteAirService {

    private final AirRecordRepository airRecordRepository;
    //实时数据 TODO 这个人数上升 需要优化
    public StatsDataVO rtdData(FieldCodeEnum item) {
        AirRecordEntity airRecordEntity = airRecordRepository.lambdaQuery()
                .eq(AirRecordEntity::getCn, CommandCodeEnum.RTD.code())
                .orderByDesc(AirRecordEntity::getAddTime).last("LIMIT 1").one();
        if (null == airRecordEntity || StrUtil.isEmpty(airRecordEntity.getCp())) {
            log.info("Air-rtd >> air is null ");
            return StatsDataVO.ofNull(null);
        }

        Duration duration = Duration.between(airRecordEntity.getAddTime(), LocalDateTime.now());
        long seconds = duration.getSeconds();
        if (seconds > 50) {
            log.info("Air-rtd >> Air rtd last > 50 s ");
            return StatsDataVO.ofNull(null);
        }

        Map<String, Map<String, String>> map = JSON.parseObject(airRecordEntity.getCp(), Map.class);
        String vs = Optional.ofNullable(map.get(item.code())).map(m -> m.get("Rtd")).orElse(null);
        if (StrUtil.isEmpty(vs)){
            log.info("Air-rtd >> item {}, value is null;", item.code());
            return StatsDataVO.ofNull(null);
        }
        double v = NumberUtil.parseDouble(vs, 0d);

        return StatsDataVO.ofOne(timeMS(airRecordEntity.getAddTime()), v);

    }

    //标准： 按小时数，烟尘30毫克每立方 a34013，  氮氧化物200mg/m3 a21002；
    public StatsDataVO statsData(FieldCodeEnum item, LocalDateTime startTime, LocalDateTime endTime){
       List<AirRecordEntity> list =  airRecordRepository.lambdaQuery()
               .eq(AirRecordEntity::getCn, CommandCodeEnum.HD.code())
               .gt(null != startTime, AirRecordEntity::getAddTime, startTime)
               .lt(null != endTime,  AirRecordEntity::getAddTime, endTime)
               .orderByDesc(AirRecordEntity::getAddTime).list();

       if (CollectionUtil.isEmpty(list)){
           log.info("Air-rtd >> air is null ");
           return StatsDataVO.ofNull(item.stant());
       }

       Map<String, Double> data = new HashMap<>();
       for (AirRecordEntity entity : list){
           if (StrUtil.isEmpty(entity.getCp())){
               continue;
           }
           Map<String, Map<String, String>> map = JSON.parseObject(entity.getCp(), Map.class);
           String vs = Optional.ofNullable(map.get(item.code())).map(m -> m.get("Avg")).orElse(null);
           double v = NumberUtil.parseDouble(vs, -100d);
           if (-100d == v){
               continue;
           }
           data.put(timeH(entity.getAddTime()), v);
       }

       return StatsDataVO.ofMap(item.stant(), data);
    }

    //查询
    public Map<String, List<AirEnvVO>> mapEnvironment(TypeToCommandEnum type, LocalDateTime startTime, LocalDateTime endTime){
        List<AirRecordEntity> list =  airRecordRepository.lambdaQuery()
                .eq(AirRecordEntity::getCn, type.command().code())
                .gt(null != startTime, AirRecordEntity::getAddTime, startTime)
                .lt(null != endTime,  AirRecordEntity::getAddTime, endTime)
                .orderByDesc(AirRecordEntity::getAddTime).last("LIMIT 600").list();

        if (CollectionUtil.isEmpty(list)){
            log.info("Air-rtd >> air is null ");
            return new HashMap<>();
        }

        FieldCodeEnum[] enums = FieldCodeEnum.values();
        Map<String, List<AirEnvVO>> mapData = new HashMap<>();
        for (FieldCodeEnum codeEnum : enums){
            mapData.put(codeEnum.code(), new ArrayList<>());
        }

        for (AirRecordEntity entity : list){
            if (StrUtil.isEmpty(entity.getCp())){
                continue;
            }
            String t = DateUtil.format(entity.getAddTime(), "yyyy-MM-dd HH:mm:ss");
            Map<String, Map<String, String>> map = JSON.parseObject(entity.getCp(), Map.class);
            for (Map.Entry<String, Map<String, String>> entry : map.entrySet()){
                List<AirEnvVO> aList = mapData.get(entry.getKey());
                if (null == aList){
                    continue;
                }

                AirEnvVO airEnvVO = new AirEnvVO();
                airEnvVO.setT(t);
                airEnvVO.setF(entry.getValue().get("Flag"));
                //set zhi
                airEnvVO.setAvg(entry.getValue().get("Avg"));
                airEnvVO.setMax(entry.getValue().get("Max"));
                airEnvVO.setMin(entry.getValue().get("Min"));
                airEnvVO.setCou(entry.getValue().get("Cou"));

                airEnvVO.setZmin(entry.getValue().get("ZsMin"));
                airEnvVO.setZmax(entry.getValue().get("ZsMax"));
                airEnvVO.setZavg(entry.getValue().get("ZsAvg"));

                //计算P
                FieldCodeEnum fieldCodeEnum = FieldCodeEnum.ofCode(entry.getKey());
                if (null != fieldCodeEnum && fieldCodeEnum.stant() > 0){
                    Double d = NumberUtil.parseDouble(airEnvVO.getAvg(), -10d);
                    airEnvVO.setP(d > fieldCodeEnum.stant() ? 1 : 0); //  0正常  1 超标
                }
                aList.add(airEnvVO);
            }

        }

        return mapData;

    }

/*    public static void main(String[] args) {
        String json = "{\"a01014\":{\"Min\":\"1.7100\",\"Avg\":\"1.7627\",\"Max\":\"1.7899\",\"Cou\":\"1.7627\",\"Flag\":\"N\"},\"a01013\":{\"Min\":\"-0.0250\",\"Avg\":\"-0.0058\",\"Max\":\"0.0250\",\"Cou\":\"-0.0058\",\"Flag\":\"N\"},\"a19001\":{\"Min\":\"9.1499\",\"Avg\":\"10.7143\",\"Max\":\"12.1999\",\"Cou\":\"10.7143\",\"Flag\":\"N\"},\"a34013\":{\"ZsMin\":\"2.6458\",\"ZsAvg\":\"3.1783\",\"ZsMax\":\"3.8951\",\"Min\":\"2.6012\",\"Avg\":\"2.7081\",\"Max\":\"2.8591\",\"Cou\":\"0.4973\",\"Flag\":\"N\"},\"a00000\":{\"Min\":\"35.8282\",\"Avg\":\"51.0117\",\"Max\":\"63.6105\",\"Cou\":\"183642.3906\",\"Flag\":\"N\"},\"a01012\":{\"Min\":\"148.7250\",\"Avg\":\"149.7605\",\"Max\":\"150.7500\",\"Cou\":\"149.7605\",\"Flag\":\"N\"},\"a01011\":{\"Min\":\"2.8099\",\"Avg\":\"3.9973\",\"Max\":\"4.9800\",\"Cou\":\"3.9973\",\"Flag\":\"N\"},\"a21002\":{\"ZsMin\":\"10.9158\",\"ZsAvg\":\"15.7117\",\"ZsMax\":\"24.7915\",\"Min\":\"9.9314\",\"Avg\":\"13.3496\",\"Max\":\"19.7309\",\"Cou\":\"2.4481\",\"Flag\":\"N\"}}";
        Map<String, Map<String, String>> map = JSON.parseObject(json, Map.class);
        System.out.println(NumberUtil.parseDouble(map.get(FieldCodeEnum.A21002.code()).get("Avg")));
        LocalDateTime dateTime1 = LocalDateTime.of(2024, 6, 28, 13, 30, 0);
        LocalDateTime dateTime2 = LocalDateTime.of(2024, 6, 28, 13, 30, 15);

        // 计算两个时间点之间的时长
        Duration duration = Duration.between(dateTime1, dateTime2);
        // 获取时间差的秒数部分
        long seconds = duration.getSeconds();

        System.out.println(seconds);
    }*/


    public static String timeMS(LocalDateTime time) {
        return time.getMinute()+":"+time.getSecond();
    }

    public static String timeH(LocalDateTime time){
        return time.getHour()+":"+"00";
    }


}
